// import axios from 'axios';

//请求的拦截器
// axios.defaults.headers.common["userId"] = localStorage.getItem("userId");
// axios.defaults.headers.common["token"] = localStorage.getItem("token");
//
// axios.post("blog/**");
// axios.get("blog/**");

/*
$.ajaxSetup({
    headers: {
        'userId': localStorage.getItem('userId'),
        'token': localStorage.getItem('token'),
    }
});
*/

// 后续所有 $.ajax 或 $.get/$.post 请求自动携带
// $.post('/blog/login');
// $.post('/blog/getAllBlogInfo');
// $.post('/blog/getUserInfo');
// $.post('/blog/getBlogInfoDetail');


/**
 * 初始化自己的页面
 */
function initMyBlogList(){
    showMyBlog();
    showAuthorInfo();
}
/**
 * 初始化博客的简单信息
 */
function initBlogList() {
    showRightBlogInfoSimple();
    showAuthorInfo();
}

/**
 *  初始化博客的详细信息
 */

function initBlogDetail() {
    showRightBlogInfo();
    showAuthorInfo();
}

/**
 * 初始化页面，展示用户的博客信息 url中给到了user的id
 */
function showMyBlog() {
    var blogCount = 0;
    $.ajax({//他是异步执行的
        type: "post",
        url: "blog/getMyBlogInfo",
        headers: {
            userId: localStorage.getItem("userId"),
            token: localStorage.getItem("token")
        },
        contentType: "application/json",
        async: false,//将他强制改为同步执行的
        /**
         *    "id": 2,
         *         "userId": 2,
         *         "title": "第2篇博客",
         *         "content": "222我是博客正⽂我是博客正⽂我是博客正文",
         *         "deleteFlag": 0,
         *         "createTime": "2025-04-02T13:18:03.000+00:00",
         *         "updateTime": "2025-04-02T13:18:03.000+00:00"
         */

        success: function (result) {
            if (!result.success) {
                alert(result.message);
                return;
            }

            var htmls = "";
            for (let r of result.data) {
                if (r.userId == localStorage.getItem("userId")) {
                    blogCount = blogCount + 1;
                }
                // console.log("blogCount= " + blogCount);

                htmls += '<div class="blog">';
                htmls += '<div class="title">' + r.title + '</div>';
                htmls += '<div class="date">' + r.createTime + '</div>';


                var content = r.content;

                if (content.length > 100) {
                    content = content.slice(0, 100) + "...";
                }

                htmls += '<div class="desc">' + content + '</div>';
                // var hr = "blog_detail.html?blogId="+r.id + '&' + location.search
                var hr = "blog_detail.html" + location.search + "?" + "blogId=" + r.id;
                htmls += '<a class="detail" href=' + hr + '>查看全文&gt;&gt;</a>';
                console.log(hr);
                htmls += '</div>';
            }

            localStorage.setItem("blogCount", blogCount);
            $(".right").html(htmls);
        },


        error: function (xhr) {
            //获取状态码
            if (xhr.status == 406) {
                alert("未登录");
                location.href = "blog_login.html";
                return;
            }
            alert("请求错误")
        }
    });

}

/**
 * 初始化页面，展示用户的博客信息 url中给到了user的id
 */
function showRightBlogInfoSimple(){
    var blogCount = 0;
    $.ajax({//他是异步执行的
        type: "post",
        url: "blog/getAllBlog",
        headers: {
            userId: localStorage.getItem("userId"),
            token: localStorage.getItem("token")
        },
        contentType: "application/json",
        async: false,//将他强制改为同步执行的
        /**
         *    "id": 2,
         *         "userId": 2,
         *         "title": "第2篇博客",
         *         "content": "222我是博客正⽂我是博客正⽂我是博客正文",
         *         "deleteFlag": 0,
         *         "createTime": "2025-04-02T13:18:03.000+00:00",
         *         "updateTime": "2025-04-02T13:18:03.000+00:00"
         */

        success: function (result) {
            if (!result.success) {
                alert(result.message);
                return;
            }

            var htmls = "";
            for (let r of result.data) {
                if (r.userId == localStorage.getItem("userId")) {
                    blogCount = blogCount + 1;
                }
                htmls += '<div class="blog">';
                htmls += '<div class="title">' + r.title + '</div>';
                htmls += '<div class="date">' + r.createTime + '</div>';


                var content = r.content;

                if (content.length > 100) {
                    content = content.slice(0,100)+"...";
                }

                htmls += '<div class="desc">' + content + '</div>';
                // var hr = "blog_detail.html?blogId="+r.id + '&' + location.search
                var hr = "blog_detail.html" + location.search + "?" + "blogId=" + r.id;
                htmls += '<a class="detail" href=' + hr + '>查看全文&gt;&gt;</a>';
                console.log(hr);
                htmls += '</div>';
            }
            // 把数目给储存下来方便获取
            localStorage.setItem("blogCount", blogCount);

            $(".right").html(htmls);
        },


        error: function (xhr) {
            //获取状态码
            if (xhr.status == 406) {
                alert("未登录");
                location.href = "blog_login.html";
                return;
            }
            alert("请求错误")
        }
    });

}

/**
 * http://127.0.0.1:8080/blog_list.html?
 * id=2&userName=lisi&password=123456
 * &githubUrl=https%3A%2F%2Fgitee.com%2Fbubble%0D%0Afish666%2Fclass-java45&deleteFlag=0
 * &createTime=2025-04-02T13%3A18%3A03.000%2B00%3A00&
 * updateTime=2025-04-02T13%3A18%3A03.000%2B00%3A00
 * 把数据放在了url中
 * 直接选择小标签
 * $(".left .card h3").text(userInfo.userName);
 * $(".left .card a").attr("href", userInfo.githubUrl);
 * 获取名字和地址
 */
function showAuthorInfo() {

    $.ajax({
        type: "post",
        contentType: "application/json",
        url: "blog/getUserInfo?userId=" + localStorage.getItem("userId"),
        headers: {
            userId: localStorage.getItem("userId"),
            token: localStorage.getItem("token")},

        success: function (result) {
            console.log("result = " + result);
            var userInfo = result.data;
            var name = userInfo.userName;

            if (userInfo.userName.length > 5) {
                name = name.slice(0,8)+"...";
            }

            console.log("name: " + name);

            $(".left .card h3").text(name);
            $(".left .card a").attr("href", userInfo.githubUrl);
            $(".left .card #count").html(
                "<span>" + localStorage.getItem("blogCount") + "</span>"
                + "<span>1</span>"
            )
        },

        error: function (xhr) {
            //获取状态码
            if (xhr.status == 406) {
                alert("未登录");
                location.href = "blog_login.html";
                return;
            }
        }

    })
    // //从url中获取值通过键值对
    // console.log("当前url:" + location.search);
    // var urlParams = new URLSearchParams(location.search);
    //
    // console.log("处理过的：" + urlParams)
    // $(".left .card #username").text(urlParams.get("userName"));
    //
    // console.log("userName=" + urlParams.get("userName"));
    //
    // $(".left .card #githubUrl").html('<a href="' + urlParams.get("githubUrl") + '" id="githubUrl">GitHub 地址</a>');
    //
    // console.log("githubUrl=" + urlParams.get("githubUrl"));
    //
    // $(".left .card #count").html(
    //     "<span>" + blogSize + "</span>"
    //     + "<span>1</span>"
    // )
    // console.log("result.size=" + blogSize);
}


/**
 * 展示右边的博客信息
 * POST /blog/getBlogInfoDetail?blogId=3&?id=2&userName=lisi
 * &password=123456&githubUrl=https%3A%2F%2Fgitee.com%2Fbubble%0D%0Afish666%2Fclass-java45&deleteFlag=0
 * &createTime=2025-04-02T13%3A18%3A03.000%2B00%3A00&updateTime=2025-04-02T13%3A18%3A03.000%2B00%3A00 HTTP/1.1
 *
 * {"id":2,"userId":2,"title":"第2篇博客","content":"222我是博客正⽂我是博客正⽂我是博客正文",
 * "deleteFlag":0,"createTime":"2025-04-02T13:18:03.000+00:00",
 * "updateTime":"2025-04-02T13:18:03.000+00:00"}
 */
function showRightBlogInfo() {
//得到信息
    $.ajax({
        type: "post",
        url: "blog/getBlogInfoDetail"+location.search,
        contentType: "application/json",
        headers: {
            userId: localStorage.getItem("userId"),
            token: localStorage.getItem("token")},

        //拼接博客信息
        success: function (result) {
            if (result == null || !result.success) {
                alert("man what can say response nothing");
                location.href = "blog_list.html";
            }

            var re = result.data;

            console.log("blog详细信息: " + re);

            //内容展示
            $(".right .content .title").text(re.title);
            $(".right .content .date").text(re.createTime);
            //使用markdown的格式来显示内容
            editormd.markdownToHTML("detail", {
                markdown: re.content,
            });
            // $(".right .content .detail").text(re.content);


            if (re.userId != localStorage.getItem("userId")) {
                return;
            }
            //下面的俩个按钮的设置
            htmls = "";
            //window.location.href='blog_update.html&blogId=1'
            var hr = "window.location.href=" + "'blog_update.html?blogId=" + re.id + "'";
            htmls += '<button onClick=' + hr + '>编辑</button>';
            htmls += '<button onClick="deleteBlog()">删除</button>';
            console.log("hr=" + htmls);
            $(".operating").html(htmls);
        },

        error: function (xhr) {
            //获取状态码
            if (xhr.status == 406) {
                alert("未登录");
                location.href = "blog_login.html";
                return;
            }
        }
    });
}

/**
 * 注销账号，把token给删了就好
 */
function logout() {
    // localStorage.removeItem("userId")
    // localStorage.removeItem("token")
    localStorage.clear();
}













